// ##数据API##

// const cookieParser = require("cookie-parser");
const query = require("../db/query");
const path = require("path");
const date = require("silly-datetime");

function Thistime() {
    //当前日期
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var mytime = date.toLocaleTimeString(); //获取当前时间
    // myDate.toLocaleString( );
    var time = year + "-" + month + "-" + day + " " + mytime;
    return time;
}
// ----------------------登陆检查拦截-----------
const loginCheckContorller = (msg) => {
    return (req, res, next) => {
        // res.cookies('key', 'value', {
        //     maxAge: 10000 * 4,
        //     signed: true,
        //     httpOnly: true
        // })
        var loginFlag = req.body.username || false;
        // console.log("loginchek", req.body, req.body.username || false);
        try {
            var url = req.url;
            var SMethoed = req.method;
            //   console.log("url", url, SMethoed);
            //   var formatData12 = JSON.stringify(req.body) || JSON.stringify(req.query); //json转字符串
            //   var formatData22 = JSON.parse(formatData12); //字符串转json，
            var Buuid = req.cookies.uuid || "0";
            var userName = req.cookies.userName || "nouser";
            // console.log("formatData22", formatData22, msg, Buuid, userName);
            const sql = `SELECT * FROM  onlineuser  WHERE  userName ='` + `${userName}` + "'"; //mysql不能又空格
            query(sql).then((data, status, err) => { //查询是否登录在线
                // console.log("登录状态检查数据库：", data[0], data.length);
                if (data == "query数据库连接错误0") {
                    res.json({
                        code: 100,
                        msg: "请求错误",
                        err,
                        status,
                    }); //不做next继续
                } else if (data.length > 0) {
                    //用户存在否
                    //检查登陆返回数据
                    const Suuid = data[0].uuid || "0";
                    const SuserName = data[0].userName;
                    const userindate = parseInt(data[0].userIndate);
                    var today = parseInt(date.format(new Date(), "YYYYMMDD"));
                    //   console.log("date", today, userindate);
                    if (Buuid !== Suuid || userName !== SuserName) {
                        //其中一个条件不对就重登录
                        // console.log("uuid或userName不存在");
                        res.cookie("userName", "", {}); //清理cookies
                        res.cookie("CName", "", {}); //清理cookies
                        if (url == "/toview" || url == "/" || url == "/loginapi" || url == "/add") {
                            // res.sendFile(path.join(process.cwd(), "src/views", "userlogin.html")); //正常未登陆或缓存信息不对都会分类拦截在此
                            res.sendFile(path.join(process.cwd(), "dist/views", "userlogin.html"));
                            // next();
                        } else {
                            //拦截费登陆请求
                            res.json({
                                code: 100,
                                msg: "未有登陆，请先登陆！",
                                info: "error",
                            });
                            // next();
                        }
                    } else if (today > userindate || loginFlag) {
                        //当前有效期小于今天或当前不是登陆页面就拦截
                        // var bodyLength = req.body;
                        res.cookie("userName", "", {}); //清理cookies
                        res.cookie("uuid", "", {}); //清理cookies
                        res.cookie("cname", "", {}); //清理cookies
                        // if (loginFlag) {
                        // } else {
                        // }
                        //有效期检查
                        //缓存信息都对
                        // console.log("账户已经过期");
                        // res.redirect("/login") upProjecData checkone  loginapi
                        if (url == "/toview" || url == "/" || url == "/loginapi" || url == "/add") { //页面访问
                            //接口分类拦截，页面和数据api
                            res.sendFile(path.join(process.cwd(), "dist/views", "userlogin.html"));
                            // res.sendFile(path.join(process.cwd(), "src/views", "userlogin.html"));
                        } else { //数据请求
                            res.json({
                                code: 100,
                                msg: "登陆过期，请重新登陆！",
                                info: "error",
                            });
                        }
                    } else {
                        next(); //符合条件系统进行下一步
                    }
                } else {
                    if (SMethoed == "GET" || SMethoed == "get") {
                        //判断是请求数据还是访问登陆首页
                        // res.sendFile(path.join(process.cwd(), "src/views", "userlogin.html"));
                        res.sendFile(path.join(process.cwd(), "dist/views", "userlogin.html"));
                    } else if (SMethoed == "post" || SMethoed == "post") {
                        res.json({
                            code: 100,
                            msg: "未有登陆，请先登陆！",
                            info: "error",
                        });
                        // next();  //异常拦截不能加next，路由其他接口会给单个请求返回多个数据导致系统停止
                    } else {
                        next(); //其他不明接口请求暂时放行
                    }
                }
            });
        } catch (error) { //错误时候执行
            res.json(error);
        } finally { //默认都执行
            //   console.log("登陆检查:", userName, Thistime());
            //   if (req.session.userinfo) {
            //     console.log("hello ", req.session.userinfo, ",welcome");
            //   } else {
            //     console.log.send("未登陆");
            //   }
        }
    };
};

module.exports = loginCheckContorller;